package top.shiyiri.community.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.shiyiri.community.bean.Event;
import top.shiyiri.community.bean.User;
import top.shiyiri.community.event.EventProducer;
import top.shiyiri.community.service.LikeService;
import top.shiyiri.community.util.CommunityUtil;
import top.shiyiri.community.util.HostHolder;

import java.util.HashMap;
import java.util.Map;

import static top.shiyiri.community.util.CommunityConstant.TOPIC_LIKE;

/**
 * @author Aunean
 * @date 2022/4/1 15:37
 */
@Controller
public class LikeController {

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private EventProducer eventProducer;

    /**
     * 点赞功能
     * @param entityType 实体类型
     * @param entityId 用户id
     * @return
     */
    @PostMapping("/like")
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId, int postId) {
        User user = hostHolder.getUser();
        //点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);
        System.out.println(user.getId() + ":" +entityType + ":" + entityId);
        //数量
        long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        //状态
        int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
        //返回的结果
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeStatus", likeStatus);

        //触发点赞事件
        if (likeStatus == 1) {
            Event event = new Event();
            event.setTopic(TOPIC_LIKE);
            event.setUserId(hostHolder.getUser().getId());
            event.setEntityType(entityType);
            event.setEntityId(entityId);
            event.setEntityUserId(entityUserId);
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("postId", postId);
            event.setData(map1);
            eventProducer.fireEvent(event);
        }
        return CommunityUtil.getJSONString(0, null, map);
    }

}
